package com.du.quant.service;

import com.du.quant.dto.StockAnalysisDTO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class DeepSeekService {

    @Value("${deepseek.api.base-url}")
    private String baseUrl;

    @Value("${deepseek.api.api-key}")
    private String apiKey;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public String analyzeStockTrading(StockAnalysisDTO analysisDTO) {
        try {
            String prompt = buildTradingPrompt(analysisDTO);
            return callDeepSeekAPI(prompt);
        } catch (Exception e) {
            log.error("调用DeepSeek API失败", e);
            throw new RuntimeException("分析服务暂时不可用，请稍后重试");
        }
    }

    private String buildTradingPrompt(StockAnalysisDTO analysisDTO) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一个专业的量化交易分析师。请基于以下股票历史数据和技术指标，结合近期题材新闻给出明确的交易建议（加仓、减仓、持有、空仓），并说明理由。\n\n");

        prompt.append("股票代码：").append(analysisDTO.getStockCode()).append("\n");
        prompt.append("股票名称：").append(analysisDTO.getStockName()).append("\n");
        prompt.append("当前价格：").append(analysisDTO.getCurrentPrice()).append("\n");
        prompt.append("涨跌幅：").append(analysisDTO.getChangeRate()).append("%\n\n");
        prompt.append("成交量（手）：").append(analysisDTO.getTurnoverNum()).append("\n\n");
        prompt.append("成交额（元）：").append(analysisDTO.getTurnoverMoney()).append("\n\n");

        // 添加技术指标计算
        Map<String, Object> technicalIndicators = calculateTechnicalIndicators(analysisDTO.getHistoryData());
        prompt.append("技术指标分析：\n");
        prompt.append("- 最近x天数据点数：x=").append(analysisDTO.getAnalyzeDays()).append("\n");
        prompt.append("- 平均成交量：").append(technicalIndicators.get("avgVolume")).append("\n");
//        prompt.append("- 价格波动率：").append(technicalIndicators.get("volatility")).append("%\n");
//        prompt.append("- 相对强弱指数(RSI)：").append(technicalIndicators.get("rsi")).append("\n\n");

        prompt.append("请按以下格式回复：\n");
        prompt.append("建议：[加仓/减仓/持有/空仓]\n");
        prompt.append("置信度：[0-100]%\n");
        prompt.append("理由：[详细的分析理由，包括技术面、基本面、支撑位、仓位管理等]\n");
        prompt.append("目标价格：[短期上方压力位的具体数值]\n");
        prompt.append("止损价格：[短期下方止损位的具体数值]");

        return prompt.toString();
    }

    private Map<String, Object> calculateTechnicalIndicators(java.util.List<com.du.quant.dto.HistoryDataDTO> historyData) {
        Map<String, Object> indicators = new HashMap<>();

        if (historyData == null || historyData.isEmpty()) {
            indicators.put("avgVolume", 0);
            indicators.put("volatility", 0);
            indicators.put("rsi", 50);
            return indicators;
        }

        // 计算平均成交量
        long totalVolume = 0;
        for (com.du.quant.dto.HistoryDataDTO data : historyData) {
            totalVolume += data.getVolume();
        }
        indicators.put("avgVolume", totalVolume / historyData.size());

        // 简化计算波动率
        double volatility = Math.random() * 30 + 10; // 模拟计算
        indicators.put("volatility", String.format("%.2f", volatility));

        // 简化计算RSI
        double rsi = Math.random() * 40 + 30; // 模拟计算
        indicators.put("rsi", String.format("%.2f", rsi));

        return indicators;
    }

    private String callDeepSeekAPI(String prompt) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(baseUrl + "/chat/completions");

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + apiKey);

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");

            Map<String, String> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", prompt);
            requestBody.put("messages", new Map[]{message});

            requestBody.put("temperature", 0.3);
            requestBody.put("max_tokens", 2000);

            String jsonBody = objectMapper.writeValueAsString(requestBody);
            httpPost.setEntity(new StringEntity(jsonBody, "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity());
                JsonNode jsonResponse = objectMapper.readTree(responseBody);

                if (response.getStatusLine().getStatusCode() == 200) {
                    return jsonResponse.path("choices").get(0)
                            .path("message").path("content").asText();
                } else {
                    log.error("API调用失败: {}", responseBody);
                    throw new RuntimeException("API调用失败: " +
                            jsonResponse.path("error").path("message").asText());
                }
            }
        }
    }
}